package config

import (
	"fmt"
	"time"

	"github.com/spf13/viper"
)

type Config struct {
	Server      ServerConfig      `mapstructure:"server"`
	Nightingale NightingaleConfig `mapstructure:"nightingale"`
	LLM         LLMConfig         `mapstructure:"llm"`
	Log         LogConfig         `mapstructure:"log"`
}

type ServerConfig struct {
	Host string `mapstructure:"host"`
	Port int    `mapstructure:"port"`
}

type NightingaleConfig struct {
	Endpoint string        `mapstructure:"endpoint"`
	Token    string        `mapstructure:"token"`
	Timeout  time.Duration `mapstructure:"timeout"`
}

type LLMConfig struct {
	ModelProvider string  `mapstructure:"model_provider"` // openai, ark
	ModelName     string  `mapstructure:"model_name"`
	APIKey        string  `mapstructure:"api_key"`
	BaseURL       string  `mapstructure:"base_url"`
	Temperature   float64 `mapstructure:"temperature"`
	MaxTokens     int     `mapstructure:"max_tokens"`
	Region        string  `mapstructure:"region"`
}

type LogConfig struct {
	Level string `mapstructure:"level"`
	File  string `mapstructure:"file"`
}

var globalConfig *Config

func Load(configPath string) (*Config, error) {
	v := viper.New()

	if configPath != "" {
		v.SetConfigFile(configPath)
	} else {
		v.SetConfigName("config")
		v.SetConfigType("yml")
		v.AddConfigPath("./config")
	}

	// 设置默认值
	v.SetDefault("server.port", 8080)
	v.SetDefault("server.host", "0.0.0.0")
	v.SetDefault("nightingale.timeout", 30*time.Second)
	v.SetDefault("llm.temperature", 0.7)
	v.SetDefault("llm.max_tokens", 4096)
	v.SetDefault("log.level", "info")

	if err := v.ReadInConfig(); err != nil {
		return nil, fmt.Errorf("failed to read config: %w", err)
	}

	var cfg Config
	if err := v.Unmarshal(&cfg); err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}

	globalConfig = &cfg
	return &cfg, nil
}

func Get() *Config {
	return globalConfig
}
